#pragma once
#include "CWindow/CWindowBase.h"
#include "Win32Utils/CStrUtils.h"
#include <vector>
#include "CBitmapDraw.h"
#include "Common.h"
#include <thread>
#include <condition_variable>
#include <mutex>

class CWindowTile :
    public CWindowBase
{
public:
    CWindowTile();
    ~CWindowTile();

    wnd_msg LRESULT OnCreate(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnClose(WPARAM wParam, LPARAM lParam);

    wnd_msg LRESULT OnSize(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnGetMinMaxInfo(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnWindowPosChanging(WPARAM wParam, LPARAM lParam);

    wnd_msg LRESULT OnEraseBkgnd(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnPaint(WPARAM wParam, LPARAM lParam);

    wnd_msg LRESULT OnLButtonDown(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnLButtonUp(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnMouseMove(WPARAM wParam, LPARAM lParam);

    void SetNotifyWnd(HWND hWnd);
    void NotifyMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
    void SetTileData(const TILE_PIXEL& tile);
    void SetPaletteData(LPCBYTE lpData);
    void SetPaletteIndex(DWORD dwIndex);
    void ClearTileData();
    void UpdateViewSize();

private:

    DECLARE_WND_MESSAGE_MAP()

    bool GetDotHit(int xPos, int yPos, POINT ptSize, POINT& ptHit);
    void DrawTile();
    bool SetBitmap32Data(LPDWORD lpData, DWORD dwSize, DWORD dwWidth, DWORD dwHeight, DWORD dwX, DWORD dwY, DWORD dwColor);

    void DrawBitmap();
    void DrawTask();

private:

    BYTE m_BkgPalette[0x10] =
    {
        0x0F,0x2A,0x12,0x3C,0x0F,0x21,0x21,0x21,0x0F,0x27,0x22,0x22,0x0F,0x22,0x22,0x22
    };

    HDC         m_hMemDC = NULL;
    HBITMAP     m_hMemBitmap = NULL;

    HDC         m_hBackDC = NULL;
    HBITMAP     m_hBackBitmap = NULL;

    HDC         m_hDrawDC = NULL;
    HBITMAP     m_hDrawBitmap = NULL;

    POINT       m_ptFocusDot = { 0, 0 };
    DWORD       m_nCurPaletteIndex = 1;

    LONG        m_MinWidth          = 64;
    LONG        m_MinHeight         = 64;

    TILE_PIXEL  m_tilePixel;
    HWND        m_NotifyWnd;
    bool        m_bLButtonDown      = false;
    bool        m_bHasData          = false;

    bool        m_bQuit = false;
    std::thread m_drawTask;
    std::mutex m_lockDraw;
    std::mutex m_lockDC;
    std::condition_variable m_cv;
};

